package com.mzx.javase.io;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * 类描述：转换流：字符流->字节流
 *  InputStreamReader是字节流到字符流的桥梁，他读取字节，并使用指定的字符集将其编码为字符，他的字符集可以由名称指定，也可以接受平台的默认字符集
 * @ClassName InputStreamReaderTest
 * @Description TODO
 * @Author 马子鑫
 * @Date 2022/7/31 19:11
 * @Version 1.0
 */
public class InputStreamReaderTest {

    public static void main(String[] args) {
        //创建流对象，默认编码UTF-8
        InputStreamReader inputStreamReader = null;
        //创建流对象，指定GBK编码
        InputStreamReader inputStreamReader2 = null;
        String path = "D:\\java\\tempdirectory\\test02.txt";
        try {
            inputStreamReader = new InputStreamReader(new FileInputStream(path));
            //创建流对象，指定GBK编码
            inputStreamReader2 = new InputStreamReader(new FileInputStream(path),"GBK");
            int read=0;
            while ((read = inputStreamReader.read()) != -1) {
                System.out.println((char)read);
            }
            while ((read = inputStreamReader2.read()) != -1) {
                System.out.println((char)read);
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (inputStreamReader2 != null) {
                try {
                    inputStreamReader2.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if (inputStreamReader != null) {
                try {
                    inputStreamReader.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }

    }
}
